<template>
  <div class="set-params" @click="$event => $event.stopPropagation()">
    <!--  header  -->
    <div class="header">
      <span class="popup-name">{{currentNode.name}}</span>
      <a-icon class="close-btn" type="close" @click="$emit('done')" />
    </div>
    <!--  body  -->
    <div class="description">
      <div class="prompt-message">请输入"$"选择数据表</div>
      <!-- 选择表 -->
      <div
        v-show="tableListVisible && currentNode.data.input.length > 0"
        class="table-list"
      >
<!--        :style="{-->
<!--        top: tableListPositionY + 'px',-->
<!--        left: tableListPositionX + 'px'-->
<!--        }"-->
        <div v-for="(item, index) in currentNode.data.input"
             :key="index"
             class="table-list-item"
             :class="{'current-active-table': activeNodeTable === index}"
             @click="clickTableName(item.tableName, $event)"
        >
          <a-tooltip
            placement="top"
            :mouse-enter-delay="1.5"
          >
            <template slot="title">
              <span>表名：{{item.tableName}}</span>
            </template>
            <div class="table-item">
              {{item.nodeName}}
            </div>
          </a-tooltip>
        </div>
        <div :class="{'current-active-table': activeNodeTable === currentNode.data.input.length}" class="table-list-item cancel-select" @click="cancelSelect" >取消选择</div>
      </div>
      <div ref="sqlCode" class="sql-statement" @keydown="listenerTableInput($event)">
        <textarea
          ref="sql"
          v-model="sql"
          class="monaco-editor"
        >
        </textarea>
      </div>

    </div>
    <!--  footer  -->
    <div class="buttons">
      <div class="btn import-btn" @click="confirm">确定</div>
      <div class="btn cancel-btn" @click="$emit('done')">取消</div>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import {Prop} from 'vue-property-decorator'
import 'codemirror/lib/codemirror.css'
import * as CodeMirror from 'codemirror'
import 'codemirror/addon/edit/matchbrackets'
import 'codemirror/addon/selection/active-line'
import 'codemirror/mode/sql/sql'


@Component({
  components: {}
})
export default class EtlSql extends Vue {
  @Prop({
      type: Object,
      default: () => {return {}}
   })
  currentNode!: any
  // sql 语句
  public sql: string =  ''
  // 编辑框
  public sqlCodeMirror: any = {}
  public positionY: number = 0
  public positionX: number = 0
  public tableListVisible: boolean = false
  public activeNodeTable: number = 0

  /**
   * Vue 组件生命周期 created
   */
  public created() {
    // 回显
    this.sql = this.currentNode.data.sql
  }

  /**
   * Vue 组件生命周期 mounted
   */
  public mounted() {
    (document.querySelector('.set-params') as HTMLDivElement).addEventListener('click', this.closeTableList)
    document.addEventListener('click', this.closeTableList)
    document.addEventListener('keyup', this.globalKeyUp)
    const that = this
    this.sqlCodeMirror = CodeMirror.fromTextArea(this.$refs.sql as HTMLTextAreaElement, {
      mode: 'text/x-sql',
      indentWithTabs: true,
      smartIndent: true,
      lineNumbers: true,
      matchBrackets: true,
      autofocus: true,
      lineWrapping: true,
      extraKeys: {
        'Enter': (cm: any) => {
          if(!this.tableListVisible) {
            cm.replaceSelection('\n')
          }
        },
      },// 自定义快捷键
    })
    if(this.sqlCodeMirror) {
      this.sqlCodeMirror.on('cursorActivity', () => {
        that.sql = that.sqlCodeMirror.getValue()
      })
    }
  }

  /**
   * Vue 组件生命周期 beforeDestroy
   */
  public beforeDestroy() {
    document.removeEventListener('click', this.closeTableList)
    document.removeEventListener('keyup', this.globalKeyUp)
  }

  /**
   * 快捷键监听  ArrowDown: 下, ArrowUp: 上,  Enter: enter
   * @param $event
   */
  public globalKeyUp($event: KeyboardEvent) {
    // 列表弹框出现
    if(this.tableListVisible) {
      if ($event.key === 'ArrowDown') {
        this.sqlCodeMirror.setCursor({ line: this.positionY, ch: this.positionX })
        if(this.activeNodeTable < this.currentNode.data.input.length){
          this.activeNodeTable += 1
        }
      }else if($event.key === 'ArrowUp') {
        this.sqlCodeMirror.setCursor({ line: this.positionY, ch: this.positionX })
        if(this.activeNodeTable  > 0) {
          this.activeNodeTable -= 1
        }
      }else if($event.key === 'Enter') {
        if(this.activeNodeTable < this.currentNode.data.input.length) {
          this.appendTable(this.currentNode.data.input[this.activeNodeTable].tableName)
        }
        this.tableListVisible = false
      }
    }

  }

  /**
   * 关闭 Modal 对话框
   */
  public closePopup() {
    this.$emit('done')
  }

  /**
   * 关闭 tableList
   */
  public closeTableList() {
    this.tableListVisible = false
  }

  /**
   * 取消选择
   */
  public cancelSelect() {
    this.closeTableList()
  }

  /**
   * 输入框 监听 '$'
   * @param $event
   */
  public listenerTableInput($event: any) {
    if($event.key === '$') {
      this.tableListVisible = true
      const position = this.sqlCodeMirror.getCursor()
      this.positionX = position.ch + 1
      this.positionY = position.line
    }
  }

  /**
   * 点击选择 表
   * @param value
   * @param $event
   */
  public clickTableName(value: string, $event: MouseEvent) {
    $event.stopPropagation()
    this.appendTable(value)
  }

  /**
   * 添加表 到 sql语句
   * @param value
   */
  public appendTable(value: string) {
    this.sqlCodeMirror.replaceSelection(value)
    this.positionX += value.length
    this.sqlCodeMirror.setCursor({ line: this.positionY, ch: this.positionX })
    this.tableListVisible = false
    setTimeout(() => {
      // CodeMirror cm-s-default CodeMirror-wrap
      this.sqlCodeMirror.focus()
    }, 1)
  }

  /**
   * 确认
   */
  public confirm() {
    this.$emit('confirm', {sql: this.sql})
  }
}
</script>

<style lang="less" scoped>
@import '@/components/studio/data/popup/setParams';

.set-params.window {
  height: 340px;
  max-width: 800px;
  min-width: 500px;
  width: 50%;
}

/* 内容 */
.description {
  font-size: 16px;
  height: calc(100% - 109px);
  padding: 12px 24px 0;
  position: relative;
  z-index: 1000;

  .prompt-message {
    margin-bottom: 12px;
  }

  /* $ 选择表 */
  .table-list {
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 3px;
    font-size: 16px;
    left: 50%;
    max-height: 200px;
    overflow-y: auto;
    position: absolute;
    top: 130px;
    transform: translateX(-50%);
    width: 200px;
    z-index: 2222;

    /* table 选项 */
    .table-list-item {
      border-bottom: 1px solid #ddd;
      cursor: pointer;
      padding: 2px 6px;
      width: 100%;

      &:hover {
        background-color: #eee;
      }

      .table-item {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    /* 当前激活 */
    .current-active-table {
      background-color: #eee;
    }

    .cancel-select {
      border-bottom: 1px solid transparent;
    }

    &::-webkit-scrollbar {
      height: 10px;
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: rgb(239, 239, 239);
      border-radius: 2px;
    }

    &::-webkit-scrollbar-thumb {
      background: #bfbfbf;
      border-radius: 6px;
    }

    &::-webkit-scrollbar-thumb:hover {
      background: #333;
    }

    &::-webkit-scrollbar-corner {
      background: #179a16;
    }
  }

  .sql-statement {
    height: calc(100% - 50px);
    overflow: hidden;
    position: relative;
    width: 100%;

    /deep/ .cm-s-default {
      height: 100%;
      overflow: hidden;
      width: 100%;
    }

    /deep/ .default {
      z-index: 2000;
    }
  }


}

</style>
